<?php

namespace STAGE\StageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use STAGE\UserBundle\Entity\user;
use STAGE\StageBundle\Form\EnseignantType;
use Symfony\Component\HttpFoundation\Response;

class EnseignantController extends Controller {

    public function indexAction() {
        return $this->render('StageBundle: Enseignant:index.html.twig');
    }

    public function newAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        $id = $request->get('id');
       
         if ($id == '')
             $enseignant = new User();
         else
            $enseignant = $em->getRepository('UserBundle:User')->find($id);
        $form = $this->createForm(new EnseignantType(), $enseignant);
        if ($request->isMethod('post')) {
            $form->bind($request);
//            if($form->isValid()){
            $enseignant = $form->getData();
            $enseignant->addRole('ROLE_ENSEIGNANT');
            $enseignant->setEnabled(true);
            $em->persist($enseignant);
            $em->flush();
            $url = $this->generateUrl('stage_enseignant_list');
            return $this->redirect($url);
//            }
        }
        return $this->render('StageBundle:Enseignant:new.html.twig', array('id' => $id, 'form' => $form->createView()));
    }

    public function listAction() {
        $em = $this->getDoctrine()->getManager();
        $request = $this->getRequest();
        $type = $request->get('type');
        $enseignants = $em->getRepository('UserBundle:User')->getEnseignant();
        if ($type != '') {
            return $this->render('StageBundle:Enseignant:page_list.html.twig', array('enseignants' => $enseignants));
        }
        return $this->render('StageBundle:Enseignant:list.html.twig', array('enseignants' => $enseignants));
    }

    public function deleteAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        $id = $request->get('id');
        $enseignant = $em->getRepository('UserBundle:User')->find($id);
        $em->remove($enseignant);
        $em->flush();
        $url = $this->generateUrl('stage_enseignant_list', array('type' => 'ajax'));
        return $this->redirect($url);
    }

}